<?php
/**
 * Implemented patterns: Lazy-load
 **/
class SiteMapHtmlReference {

    private $_cache = false;

    private $_loaded = false;

    private $_uri;

    private $_links;

    public function __construct($uri) {
        $this->_cache = Configuration::get('Framework.SiteMap.SiteMapHtmlReference._cache');
        $this->_uri = $uri;
    }

    public function __get($name) {

        if (!$this->_loaded) {

            // Locals
            $Cache = null;
            $cached = null;

            // Try to get data from cache if cache is enabled
            if ($this->_cache) {
                $Cache = Cache::load();
                $cached = $Cache->get($this->_uri);
            }

            if (null != $cached) {

                Trace::writeLine("Framework.SiteMap.SiteMapHtmlReference.__get $this->_uri from cache");

                $this->_links = $cached;
            } else {

                Trace::writeLine("Framework.SiteMap.SiteMapHtmlReference.__get $this->_uri from web");

                $this->parse();

                // Add data to cache if cache is enabled
                if (null != $Cache) {
                    $Cache->set($this->_uri, $this->_links);
                    $Cache->save();
                }
            }

            $this->_loaded = true;
        }

        if ("links" == $name) {
            return $this->_links;
        }

        return null;
    }

    public static function onFilterData($node) {
    }

    /**
     * Parses the given URI
     **/
    private function parse() {
        $document = file_get_html($this->_uri);

        $i = 0;
        while (true) {

            $page = $document->find('url', $i);

            // Process extracted data
            if (null != $page) {
                $nodeLocation = $page->find('loc', 0);
                if (null != $nodeLocation) {
                    $this->_links[] = $nodeLocation->innertext();
                }
            } else {
                break;
            }

            $i++;
        }
    }
}
?>